Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.

题目大意:删除链表的倒数第n个节点,返回头指针,给定n是有效的,要求只能遍历一遍链表

题目难度:Easy

/**
 * Created by gzdaijie on 16/5/5
 * 2个指针,一快一慢,快的提前走n步,走完n步后,两个一起走,直到快的走到终点
 * 这时,慢的指针的下一个节点,就是待删除的节点
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode headNode = new ListNode(0);
        ListNode slow = headNode;
        ListNode fast = headNode;
        headNode.next = head;

        while (fast.next != null) {
            fast = fast.next;
            if (n <= 0) {
                slow = slow.next;
            }
            --n;
        }
        if (slow.next != null) {
            slow.next = slow.next.next;
        }
        return headNode.next;
    }
}
gzdaijie            updated 2016-05-05 22:17:04

results matching ""

    No results matching ""